package org.fat.nerd.actd.sharding.init;

import lombok.extern.slf4j.Slf4j;
import org.fat.nerd.actd.sharding.beans.dto.TenantDatasourceDTO;
import org.fat.nerd.actd.sharding.beans.entity.Datasource;
import org.fat.nerd.actd.sharding.config.DataSourceContextHolder;
import org.fat.nerd.actd.sharding.config.DynamicDataSource;
import org.fat.nerd.actd.sharding.constant.GlobalConstant;
import org.fat.nerd.actd.sharding.dao.DatasourceMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
@Order(value = 1)
@Slf4j
public class SystemInitRunner implements CommandLineRunner {

    @Resource
    private DatasourceMapper tenantDatasourceMapper;

    @Autowired
    private DynamicDataSource dynamicDataSource;

    public void run(String... args) throws Exception {
        //租户端不进行服务调用
        log.info("==服务启动后，初始化数据源==");
        //切换默认数据源 即tenant库的数据源，用于查询tenant表中的所有tenant数据库配置
        DataSourceContextHolder.setDBType(GlobalConstant.TENANT_CONFIG_KEY);
        //设置所有数据源信息
        log.info("获取当前数据源：" + DataSourceContextHolder.getDBType());
        List<Datasource> tenantInfoList = tenantDatasourceMapper.selectList(null);
        for (Datasource info : tenantInfoList) {
            TenantDatasourceDTO tenantDatasourceDTO = new TenantDatasourceDTO();
            BeanUtils.copyProperties(info, tenantDatasourceDTO);
            dynamicDataSource.addDataSource(tenantDatasourceDTO);
        }
        log.info("动态数据源对象中的所有数据源, 已加载数据源个数: {}", dynamicDataSource.getBackupTargetDataSources().size());
        log.info(dynamicDataSource.getBackupTargetDataSources().toString());
        log.info("初始化多租户数据库配置完成...");
    }
}
